<template>
  <div class="workflow-management">
    <div class="header">
      <h2>工作流管理</h2>
      <el-button type="primary" @click="createWorkflow">
        创建工作流
      </el-button>
    </div>

    <!-- 工作流列表 -->
    <el-table 
      v-loading="loading"
      :data="workflows" 
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="category" label="模板类型">
        <template #default="scope">
          {{ getCategoryLabel(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="created_at" label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button 
            size="small" 
            @click="editWorkflow(scope.row)"
          >编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deleteWorkflow(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-form 
        :model="workflowForm" 
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="workflowForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="workflowForm.description" 
            type="textarea" 
          />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select 
            v-model="workflowForm.type"
            placeholder="请选择模板类型"
          >
            <el-option 
              v-for="type in templateTypes" 
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button 
          type="primary" 
          :loading="saving"
          @click="saveWorkflow"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'

const router = useRouter()
const workflows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const workflowForm = ref({
  name: '',
  description: '',
  type: ''
})

const templateTypes = [
  { label: '文生图', value: 'text2img' },
  { label: '图生图', value: 'img2img' },
  { label: '人物肖像', value: 'portrait' }
]

const loading = ref(false)
const saving = ref(false)
const formRef = ref(null)

// 添加表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ]
}

// 获取工作流列表
const fetchWorkflows = async () => {
  try {
    const response = await request('/api/v1/workflows')
    workflows.value = response
  } catch (error) {
    console.error('获取工作流列表失败:', error)
    ElMessage.error('获取工作流列表失败')
  }
}

// 创建工作流
const createWorkflow = () => {
  router.push('/workflow/create')
}

// 编辑工作流
const editWorkflow = (workflow) => {
  router.push(`/workflow/${workflow.id}`)
}

// 保存工作流
const saveWorkflow = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }
  
  saving.value = true
  try {
    const url = workflowForm.value.id 
      ? `/api/v1/workflows/${workflowForm.value.id}`
      : '/api/v1/workflows'
    
    await request(url, {
      method: workflowForm.value.id ? 'PUT' : 'POST',
      body: JSON.stringify(workflowForm.value)
    })
    
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchWorkflows()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 删除工作流
const deleteWorkflow = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个工作流吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await request(`/api/v1/workflows/${id}`, {
      method: 'DELETE'
    })
    
    ElMessage.success('删除成功')
    fetchWorkflows()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const categoryMap = {
    'text2img': '文生图',
    'img2img': '图生图',
    'portrait': '人物肖像'
  }
  return categoryMap[category] || category
}

onMounted(() => {
  fetchWorkflows()
})
</script>

<style scoped>
.workflow-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style> 